package news.yp.newsproject.presenter.presenter;

import android.annotation.SuppressLint;
import android.util.Log;

import com.news.yp.baselibrary.base.BasePresenter;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import news.yp.newsproject.bean.ResponsePageData;
import news.yp.newsproject.bean.ResponseSectionData;
import news.yp.newsproject.presenter.model.ModelPresenter;

public class NewsPresenter extends BasePresenter<CenterPresenter.ViewPresenter> implements CenterPresenter.DataPresenter {
    private CenterPresenter.ModelPresenter mModel;

    public NewsPresenter() {
        mModel = new ModelPresenter();
    }

    //解耦
    @SuppressLint("CheckResult")
    public void getSection() {
        getView().onLoading();
        mModel.getSectionData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseSectionData>() {
                    @Override
                    public void accept(ResponseSectionData responseSectionData) throws Exception {
                        if (responseSectionData == null) {
                            throw new Exception("请求失败");
                        }
                        if (responseSectionData.getCode() == 1) {
                            throw new Exception("返回错误码1");
                        }
                        getView().onSuccess(responseSectionData);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        getView().onError();
                    }
                });
    }

    /**
     * 拉取分页消息
     *
     * @param firstSection
     */
    @SuppressLint("CheckResult")
    public void getpage(String firstSection, int num, int page) {
        mModel.getpageData(firstSection, num, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponsePageData>() {
                    @Override
                    public void accept(ResponsePageData responsePageData) throws Exception {
                        if (responsePageData == null) {
                            throw new Exception("返回异常");
                        }
                        if (responsePageData.getCode() == 1) {
                            throw new Exception("没有获取到数据");
                        }
                        getView().onPageSuccess(responsePageData);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e("TAG", "异常" + throwable.getMessage());
                        getView().onError();
                    }
                });
    }
}
